import base64
import urllib
import requests
import traceback
API_KEY = "9DdB9EsrxD5J1kOqhSsz4zDc"
SECRET_KEY = "To5WBPW9Sak9t2FY0YD2caf3KWnvfTjf"

def get_baidu3_location_json(img_path):
        
    url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general?access_token=" + get_access_token()
    img_base64 = get_file_content_as_base64(img_path,True)
    # image 可以通过 get_file_content_as_base64("C:\fakepath\17399388901250215.png",True) 方法获取
    payload=f'image={img_base64}&detect_direction=false&detect_language=false&vertexes_location=false&paragraph=false&probability=false'
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'application/json'
    }
    
    response = requests.request("POST", url, headers=headers, data=payload.encode("utf-8"))
    
    # print(response.text)
    return response.json() 
    

def get_file_content_as_base64(path, urlencoded=False):
    """
    获取文件base64编码
    :param path: 文件路径
    :param urlencoded: 是否对结果进行urlencoded 
    :return: base64编码信息
    """
    with open(path, "rb") as f:
        content = base64.b64encode(f.read()).decode("utf8")
        if urlencoded:
            content = urllib.parse.quote_plus(content)
    return content

def get_access_token():
    """
    使用 AK，SK 生成鉴权签名（Access Token）
    :return: access_token，或是None(如果错误)
    """
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}
    return str(requests.post(url, params=params).json().get("access_token"))

if __name__ == '__main__':

    filepath=r'D:\gitee\w1\walmartca\screenshot\17399389691367764.PNG'
    json_result=get_baidu3_location_json(filepath)
    print(json_result)
    filepath=r'C:\Users\Administrator\Desktop\zj\3.png'
    json_result=get_baidu3_location_json(filepath)
    itemlocation=get_text_location_inwindow(json_result,'打开')
    print(itemlocation['location'])